<script lang="ts" setup>
import type { UploadProps } from 'ant-design-vue';

import { computed, ref } from 'vue';

import { Page } from '@vben/common-ui';

import { UploadOutlined } from '@ant-design/icons-vue';
import { Card, Empty, message } from 'ant-design-vue';
import moment from 'moment';
import { v4 as uuidv4 } from 'uuid';

import { getActiveListApi, getOssSignApi, uploadImagesApi } from '#/api';

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
type NotificationType = 'error' | 'info' | 'success' | 'warning';

const handleChange = (value: string) => {
  console.log(`selected ${value}`);
};
const sign = ref({});
const placeId = ref([]);
const host = ref('https://xiaosongguo.oss-cn-beijing.aliyuncs.com');

const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const spinning = ref<boolean>(false);

// const options = [...Array(25)].map((_, i) => ({ value: (i + 10).toString(36) + (i + 1) }));
const options = ref<any>([
  // { value: 'jack2', label: 'Jack1' },
  // { value: 'lucy2', label: 'Lucy1' },
  // { value: 'tom2', label: 'Tom1' },
]);
getActiveListApi().then((res) => {
  const list = res.data;
  options.value =
    list.length > 0
      ? list.map((item: any) => {
          return {
            value: item.id,
            label: item.name,
          };
        })
      : [];
  console.log(res.data);
});
const fileList1 = ref<UploadProps['fileList']>([
  // {
  //   uid: '-1',
  //   name: 'xxx.png',
  //   status: 'done',
  //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  //   thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  // },
  // {
  //   uid: '-2',
  //   name: 'yyy.png',
  //   status: 'done',
  //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  //   thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  // },
]);
function handleBeforeUpload(files) {
  spinning.value = true;
  return new Promise(async (resolve, reject) => {
    try {
      const fileExt = files.name.split('.').pop();
      console.log('fileExt>>', fileExt);

      const img = new Image();
      img.src = URL.createObjectURL(files); // 创建临时URL加载图片
      img.addEventListener('load', async () => {
        const width = img.width;
        const height = img.height;
        console.log(`Image Width: ${width}, Height: ${height}`);
        console.log('img key>>', `${uuidv4()}_${width}x${height}.${fileExt}`);

        const res = await getOssSignApi({
          dirname: 'upload',
          // ext: fileExt,
          full_name: `upload/${moment().format('YYYYMMDD')}/${uuidv4()}_${width}x${height}.${fileExt}`, // 拼接宽高到key中
        });

        if (!res || !res.signature) {
          throw new Error('获取上传签名失败');
        }

        host.value = res.host;
        sign.value = res;
        files.url = `${res.host}/${res.key}`;
        resolve(); // 返回处理后的 FormData
      });

      img.onerror = () => {
        message.error('无法加载图片以获取宽高');
        reject(new Error('无法加载图片以获取宽高'));
      };
    } catch (error) {
      message.error(`文件上传前处理失败：${error.message}`);
      reject(error);
    }
  });
}

function getParams(files) {
  // console.log(2);
  return {
    OSSAccessKeyId: sign.value.accessKeyId,
    key: sign.value.key,
    policy: sign.value.policy,
    signature: sign.value.signature,
    success_action_status: '200',
  };
}

function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.addEventListener('load', () => resolve(reader.result));
    reader.onerror = (error) => reject(error);
  });
}

const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
const handleUplaodImage = async (obj) => {
  spinning.value = false;
};
const handlePreview = async (file: any) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string;
  }
  previewImage.value = file.thumbUrl;
  previewVisible.value = true;
  previewTitle.value =
    file.name || file.url.slice(Math.max(0, file.url.lastIndexOf('/') + 1));
};
const getSuccessCount = computed(() => {
  return fileList1.value?.filter((file) => file.status === 'done').length || 0;
});
const getErrorCount = computed(() => {
  return fileList1.value?.filter((file) => file.status === 'error').length || 0;
});

const isUpLoading = computed(() => {
  const len =
    fileList1.value?.filter((file) => file.status === 'uploading').length || 0;
  return len > 0;
});

const hanldeSubmitUpLoad = () => {
  if (placeId.value <= 0) {
    message.warning(`请选选择场次`);
    return false;
  }
  // 获取所有上传成功的文件URL
  const successUrls = fileList1.value
    .filter((file) => file.status === 'done')
    .map((file) => file.url);
  uploadImagesApi({ id: placeId.value, images: successUrls.join('|') })
    .then(() => {
      message.success(`上传成功`);
      fileList1.value = [];
    })
    .catch(() => {
      message.error(`上传失败`);
    });
};
</script>

<template>
  <Page auto-content-height>
    <template #title>
      <div class="title-box">
        <div class="">
          <div>合计：{{ fileList1.length }}</div>
          <div>
            上传成功：<span style="color: green">{{ getSuccessCount }}</span>
          </div>
          <div>
            上传失败：<span style="color: red">{{ getErrorCount }}</span>
          </div>
        </div>
        <div class="title-item">
          <!-- <div class="active-con">
            <div>活动：</div>
              <div class="active-box">
                <a-select
                  v-model:value="value"
                  style="width: 100%"
                  placeholder="请选择"
                  :options="options"
                  @change="handleChange"
                ></a-select>
              </div>
          </div> -->
          <div class="active-con" style="padding-top: 16px">
            <div>场次：</div>
            <div class="active-box">
              <a-select
                v-model:value="placeId"
                :options="options"
                placeholder="请先选择活动"
                style="width: 100%"
                @change="handleChange"
              />
            </div>
          </div>
        </div>

        <!-- <div class="">
          <div class="upload-btn">
            <div> 
              <UploadOutlined  :style="{fontSize: '18px', color: '#08c'}"  />
            </div>
            <div style="padding-top: 8px">选择上传图片</div>
          </div>
        </div> -->

        <div class="flex items-center justify-center">
          <a-button
            :disabled="isUpLoading || getSuccessCount <= 0"
            size="large"
            type="primary"
            @click="hanldeSubmitUpLoad"
          >
            上传
          </a-button>
        </div>
      </div>
    </template>
    <Card class="mb-5">
      <!-- <div> <a-empty :image="simpleImage" description="请选择图片上传"/></div> -->
      <a-spin :spinning="spinning">
        <a-upload
          v-model:file-list="fileList1"
          :action="host"
          :before-upload="handleBeforeUpload"
          :data="getParams"
          :max-count="1000"
          accept="image/png, image/jpeg"
          class="upload-list-inline"
          list-type="picture"
          multiple
          @change="handleUplaodImage"
          @preview="handlePreview"
        >
          <div v-if="fileList1.length < 1000" class="upload-btn">
            <div>
              <UploadOutlined :style="{ fontSize: '18px', color: '#08c' }" />
            </div>
            <div style="padding-top: 2px">
              选择上传图片(Max: {{ fileList1.length }}/1000)
            </div>
          </div>
        </a-upload>
      </a-spin>
      <!-- <div>
        {{ fileList1 }}
      </div> -->
    </Card>
    <a-modal
      :footer="null"
      :open="previewVisible"
      :title="previewTitle"
      @cancel="handleCancel"
    >
      <img :src="previewImage" alt="example" style="width: 100%" />
    </a-modal>
  </Page>
</template>
<style lang="less" scoped>
.title-box {
  display: flex;
  justify-content: space-around;
  .active-con {
    display: flex;
    align-items: center;
  }
  .active-box {
    width: 300px;
  }
  .upload-btn {
    width: 90px;
    height: 80px;
    background: #f1f1f1;
    border-radius: 10px;
    text-align: center;
    font-size: 10px;
    cursor: pointer;
    padding-top: 15px;
  }
}
/* tile uploaded pictures */
.upload-list-inline :deep(.ant-upload-list) {
  display: flex;
  flex-wrap: wrap;
}

.upload-list-inline :deep(.ant-upload-list-item) {
  float: left;
  width: 200px;
  margin-right: 8px;
}
.upload-list-inline :deep(.ant-upload-list-item) {
  float: left;
  width: 200px;
  margin-right: 8px;
}
.upload-list-inline [class*='-upload-list-rtl'] :deep(.ant-upload-list-item) {
  float: right;
}
.upload-btn {
  width: 80px;
  height: 80px;
  background: #f1f1f1;
  border-radius: 10px;
  text-align: center;
  font-size: 10px;
  cursor: pointer;
  padding-top: 20px;
}
</style>
